-module(cloap_event_logger).
-behaviour(gen_event).
-export([
         add_handler/0,
         delete_handler/0
        ]).
-export([init/1, handle_event/2, handle_call/2, 
         handle_info/2, code_change/3, terminate/2
        ]).
-include("cloap_record.hrl").
-record(state, {}).


add_handler() -> 
    cloap_event:add_handler(?MODULE, []).
delete_handler() ->
    cloap_event:delete_handler(?MODULE, []).


init([]) ->
    {ok, #state{}}.
handle_event({login, Who}, State) ->
    cloap_store:insert(#action_log{who = Who, app = <<"login">>, action = <<"login">>, time = erlang:now()}),
    {ok, State};
handle_event({action, Who, App, Action, Data}, State) ->
    lager:warning("Event action is ~p ~n", [Action]),
    case re:run(Action, "((\.(create|destroy|update))|(^(POST|PUT|DELETE)))") of
        nomatch -> ok;
        _Match ->
            cloap_store:insert(#action_log{who = Who, app = App, action = Action, data = Data, time = erlang:now()})
    end,
    {ok, State}.
handle_call(_Request, State) ->
    {ok, ok, State}.
handle_info(_Info, State) ->
    {ok, State}.
terminate(_Reason, _State) ->
    ok.
code_change(_OldVsn, State, _Extra) ->
    {ok, State}.



